﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using System.Diagnostics;
using VSSAHT.Transfer;
using VSSAHT.DataAccess;
using VSS_AHT.Properties;
using CatelCrm.Data;
using CatelCrm.Helpers;
using VSSAHT;
using VSS_AHT.Reports;
using CrystalDecisions.CrystalReports.Engine;
using VSS_AHT.ReportForms;
using System.IO.Ports;

namespace VSS_AHT
{
    public partial class FormScaleTicket : BaseForm
    {

        #region Singleton Members
        private static volatile FormScaleTicket instance;
        private static object syncRoot = new Object();
        // public SerialPort Port;
        public static FormScaleTicket Instance
        {
            get
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new FormScaleTicket();
                }

                return instance;
            }
        }
        #endregion

        #region Variables

        const string _ticketTypes = "PRCISITRTI";
        //private VSS_AHT.Data.ScaleProcessing _scaleProcessing;
        private DataTable table = new DataTable("Sheet1");
        private bool _exportViaRequire;
        private string _data = String.Empty;
        private bool isSelectGrid = false;
        private string textSequeneRow = String.Empty;
        private IList<ScaleTicketDTO> _listTemp;
        private bool remind = false;
        private bool remindLoad = true;
        private RequireNumberDTO _require;
        #endregion

        #region Constructor & destructor

        public FormScaleTicket()
            : base()
        {
            InitializeComponent();

            //   _scaleProcessing = new VSS_AHT.Data.ScaleProcessing();
            //   _scaleProcessing.GetScaleStatus = new VSS_AHT.Data.ScaleProcessing.GetScaleStatusDelegate(GetStatus);
            //   _scaleProcessing.ParseData = new VSS_AHT.Data.ScaleProcessing.ParseDataDelegate(ParseData);

            svc.AddService(typeof(IItemDataAccess), new ItemDataAccess());
            svc.AddService(typeof(ICustomerDataAccess), new CustomerDataAccess());
            svc.AddService(typeof(IModelVehicleDataAccess), new ModelVehicleDataAccess());
            svc.AddService(typeof(ILocationDataAccess), new LocationDataAccess());
            svc.AddService(typeof(IRequireNumberDataAccess), new RequireNumberDataAccess());
            svc.AddService(typeof(IScaleTicketDataAccess), new ScaleTicketDataAccess());
        }

        #endregion

        #region Virtual Overrides

        protected override void OnLoadData()
        {
            // Permission
            this.MaximizeBox = true;
            if (Common.UserLogin.Role != null)
            {
                // this.chkManual.Visible = Common.UserLogin.Role.Permitted.ManualScale;
                this._exportViaRequire = Common.UserLogin.Role.Permitted.ExportExcelViaRequire;
            }

            // Init table
            table.Columns.Add("TicketID", typeof(string));
            table.Columns.Add("Requirement", typeof(string));
            table.Columns.Add("ItemNumber", typeof(string));
            table.Columns.Add("ItemName", typeof(string));
            table.Columns.Add("VendorID", typeof(string));
            table.Columns.Add("VendorName", typeof(string));
            table.Columns.Add("InTime", typeof(DateTime));
            table.Columns.Add("OutTime", typeof(DateTime));
            table.Columns.Add("Weight1", typeof(decimal));
            table.Columns.Add("Weight2", typeof(decimal));
            table.Columns.Add("BalanceWeight", typeof(decimal));
            table.Columns.Add("VehicleNumber", typeof(string));
            table.Columns.Add("LocationID", typeof(string));
            table.Columns.Add("Qty1", typeof(decimal));
            table.Columns.Add("Unit1", typeof(string));
            table.Columns.Add("Qty2", typeof(decimal));
            table.Columns.Add("Unit2", typeof(string));
            table.Columns.Add("QtyPct", typeof(decimal));

            // Load scale type. Value 0 is Receives and value 1 is Invoices, value 2 is Transfer
            this.cboTicketType.Properties.Items.Add("NHẬP (PR)"); // Purchase Receive
            this.cboTicketType.Properties.Items.Add("XUẤT SỬ DỤNG (CI)"); // Consumer Invoice
            this.cboTicketType.Properties.Items.Add("XUẤT BÁN (SI)"); // Sales Invoice
            this.cboTicketType.Properties.Items.Add("CHUYỂN NHẬP (TR)");
            this.cboTicketType.Properties.Items.Add("CHUYỂN XUẤT (TI)");
            

            // Load Locations List
            var modelvehicles = (svc.GetService(typeof(IModelVehicleDataAccess)) as IModelVehicleDataAccess).GetAll();
            this.lookUpModelVehicleCode.Properties.DataSource = modelvehicles;
            this.lookUpModelVehicleCode.Properties.DisplayMember = "ModelVehicleNumber";
            this.lookUpModelVehicleCode.Properties.ValueMember = "ModelVehicleNumber";
            this.lookUpModelVehicleCode.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoComplete;

            // Load Items List
            var items = (svc.GetService(typeof(IItemDataAccess)) as IItemDataAccess).GetAll();
            foreach (var item in items)
            {
                this.lookUpItemNumber.Items.Add(new Femiani.Forms.UI.Input.AutoCompleteEntry(item.ItemName + ",  " + item.ItemNumber, item.ItemName, item.ItemName));
            }
            this.lookUpItemNumber.Tag = items;

            // Load Unit 2
            this.cboUnit2.Properties.Items.AddRange(items.Select(x => x.ItemUnit).Distinct().ToArray<string>());

            // Load Vendors List
            var vendors = (svc.GetService(typeof(ICustomerDataAccess)) as ICustomerDataAccess).GetAll();
            foreach (var vendor in vendors)
            {
                this.lookUpVendorNumber.Items.Add(new Femiani.Forms.UI.Input.AutoCompleteEntry(vendor.CustomerName + ",  " + vendor.CustomerCode, vendor.CustomerName, vendor.CustomerName));
            }
            this.lookUpVendorNumber.Tag = vendors;

            // Load Locations List
            var locations = (svc.GetService(typeof(ILocationDataAccess)) as ILocationDataAccess).GetAll();
            this.lookUpLocationCode.Properties.DataSource = locations;
            this.lookUpLocationCode.Properties.DisplayMember = "LocationCode";
            this.lookUpLocationCode.Properties.ValueMember = "LocationName";
            this.lookUpLocationCode.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoComplete;

            // Load Require List
            var requires = (svc.GetService(typeof(IRequireNumberDataAccess)) as IRequireNumberDataAccess).GetAll();
            this.lookUpRequireCode.Properties.DataSource = requires;
            this.lookUpRequireCode.Properties.DisplayMember = "RequireCode";
            this.lookUpRequireCode.Properties.ValueMember = "RequireName";
            this.lookUpRequireCode.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoComplete;
            this.chkManualVehicle.Checked = true;
            this.dateScale.DateTime = DateTime.Now;
            this.lookUpModelVehicleCode.Visible = false;

            this.AddNew();

            base.OnLoadData();
        }

        protected override void OnEvents()
        {
            this.dateScale.DateTimeChanged += new EventHandler(dateScale_DateTimeChanged);

            // Logic events
            this.chkAutomatic.CheckedChanged += new EventHandler(chkAutomatic_CheckedChanged);
            this.chkManual.CheckedChanged += new EventHandler(chkManual_CheckedChanged);
            this.chkManualRequire.CheckedChanged += new EventHandler(chkManualRequire_CheckedChanged);
            this.chkManualVehicle.CheckedChanged += new EventHandler(chkManualVehicle_CheckedChanged);
            this.chkFilterScaleDate.CheckedChanged += new EventHandler(chkFilterScaleDate_CheckedChanged);
            this.chkZeroOrNone.CheckedChanged += new EventHandler(chkZeroOrNone_CheckedChanged);
            this.txtKg.TextChanged += new EventHandler(ReduceKg_TextChanged);
            this.txtPercent.TextChanged += new EventHandler(txtPercent_TextChanged);
            this.txtKg.LostFocus += new EventHandler(txtKg_LostFocus);
            this.txtPercent.LostFocus += new EventHandler(txtPercent_LostFocus);
            this.txtVehicleNumber.LostFocus += new EventHandler(txtVehicleNumber_LostFocus);
            this.txtVehicleNumber.TextChanged += new EventHandler(txtVehicleNumber_TextChanged);
            this.lookUpModelVehicleCode.LostFocus += new EventHandler(lookUpModelVehicleCode_LostFocus);
            // Number events
            this.numFirstWeight.ValueChanged += new EventHandler(EditWeightChanged);
            this.numSecondWeight.ValueChanged += new EventHandler(EditWeightChanged);
            this.numFirstWeight.LostFocus += new EventHandler(numFirstWeight_LostFocus);
            this.numSecondWeight.LostFocus += new EventHandler(numSecondWeight_LostFocus);
            this.numBalanceWeight.TextChanged += new EventHandler(numBalanceWeight_TextChanged);
            this.rdt0.CheckedChanged += new EventHandler(rdt0_CheckedChanged);
            this.rdt1.CheckedChanged += new EventHandler(rdt1_CheckedChanged);
            // Select ID
            this.lookUpModelVehicleCode.EditValueChanged += new EventHandler(lookUpModelVehicleCode_EditValueChanged);
            this.lookUpItemNumber.TextChanged += new EventHandler(lookUpItemNumber_TextChanged);
            this.lookUpVendorNumber.TextChanged += new EventHandler(lookUpVendorNumber_TextChanged);
            this.lookUpLocationCode.EditValueChanged += new EventHandler(lookUpLocationCode_EditValueChanged);
            this.lookUpRequireCode.EditValueChanged += new EventHandler(lookUpRequireCode_EditValueChanged);
            this.cboTicketType.SelectedIndexChanged += new EventHandler(cboTicketType_SelectedIndexChanged);
            this.txtUnit1.TextChanged += new EventHandler(Unit1_TextChanged);
            this.txtUnit2.TextChanged += new EventHandler(Unit2_TextChanged);
            //this.cboUnit2.TextChanged += new EventHandler(Unit2_TextChanged);
            this.txtQty2.TextChanged += new EventHandler(txtQty2_TextChanged);
            this.txtQty1.TextChanged += new EventHandler(txtQty1_TextChanged);
            // Button Click
            this.btnReset1.Click += new EventHandler(btnReset1_Click);
            this.btnReset2.Click += new EventHandler(btnReset2_Click);
            this.btnSaveAndPrint.Click += new EventHandler(btnSaveAndPrint_Click);
            this.btnSave.Click += new EventHandler(btnSave_Click);
            this.btnNew.Click += new EventHandler(btnNew_Click);
            this.btnPrint.Click += new EventHandler(btnPrint_Click);
            this.btnReload.Click += new EventHandler(btnReload_Click);

            this.btnClose.Click += new EventHandler(delegate
            {
                this.Close();
            });

            // Grid events
            this.gridView1.FocusedRowChanged += new DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventHandler(gridView1_FocusedRowChanged);
            this.gridView1.MouseDown += new MouseEventHandler(gridView1_MouseDown);

            this.Disposed += new EventHandler(delegate { instance = null; });

            base.OnEvents();
        }

        void txtVehicleNumber_TextChanged(object sender, EventArgs e)
        {
            if (txtVehicleNumber.Text.Length > 0)
            {
                remind = true;
            }
        }

        void btnReload_Click(object sender, EventArgs e)
        {
            // Load Locations List
            var modelvehicles = (svc.GetService(typeof(IModelVehicleDataAccess)) as IModelVehicleDataAccess).GetAll();
            this.lookUpModelVehicleCode.Properties.DataSource = modelvehicles;
            this.lookUpModelVehicleCode.Properties.DisplayMember = "ModelVehicleNumber";
            this.lookUpModelVehicleCode.Properties.ValueMember = "ModelVehicleNumber";
            this.lookUpModelVehicleCode.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoComplete;

            // Load Items List
            var items = (svc.GetService(typeof(IItemDataAccess)) as IItemDataAccess).GetAll();
            this.lookUpItemNumber.Items.Clear();
            foreach (var item in items)
            {
                this.lookUpItemNumber.Items.Add(new Femiani.Forms.UI.Input.AutoCompleteEntry(item.ItemName + ",  " + item.ItemNumber, item.ItemName, item.ItemName));
            }
            this.lookUpItemNumber.Tag = items;

            // Load Unit 2
            this.cboUnit2.Properties.Items.AddRange(items.Select(x => x.ItemUnit).Distinct().ToArray<string>());

            // Load Vendors List
            var vendors = (svc.GetService(typeof(ICustomerDataAccess)) as ICustomerDataAccess).GetAll();
            this.lookUpVendorNumber.Items.Clear();
            foreach (var vendor in vendors)
            {
                this.lookUpVendorNumber.Items.Add(new Femiani.Forms.UI.Input.AutoCompleteEntry(vendor.CustomerName + ",  " + vendor.CustomerCode, vendor.CustomerName, vendor.CustomerName));
            }
            this.lookUpVendorNumber.Tag = vendors;

            // Load Locations List
            var locations = (svc.GetService(typeof(ILocationDataAccess)) as ILocationDataAccess).GetAll();
            this.lookUpLocationCode.Properties.DataSource = locations;
            this.lookUpLocationCode.Properties.DisplayMember = "LocationCode";
            this.lookUpLocationCode.Properties.ValueMember = "LocationName";
            this.lookUpLocationCode.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoComplete;
           
            // Load Require List
            var requires = (svc.GetService(typeof(IRequireNumberDataAccess)) as IRequireNumberDataAccess).GetAll();
            this.lookUpRequireCode.Properties.DataSource = requires;
            this.lookUpRequireCode.Properties.DisplayMember = "RequireCode";
            this.lookUpRequireCode.Properties.ValueMember = "RequireName";
            this.lookUpRequireCode.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoComplete;
        }

        void rdt1_CheckedChanged(object sender, EventArgs e)
        {
            this.txtTicketID.Text = TicketID;
        }

        void rdt0_CheckedChanged(object sender, EventArgs e)
        {
            this.txtTicketID.Text = TicketID;
        }

        protected void numBalanceWeight_TextChanged(object sender, EventArgs e)
        {
            if (Convert.ToDecimal(this.numBalanceWeight.EditValue) > 0)
            {
                this.btnPrint.Enabled = true;
                if (this.txtUnit1.Text.Trim() == "TON")
                {
                    txtQty1.EditValue = ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) - ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit2.Text.Trim() == "TON")
                {
                    txtQty2.EditValue = ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) - ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit1.Text.Trim() == "KG")
                {
                    txtQty1.EditValue = (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) - (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit2.Text.Trim() == "KG")
                {
                    txtQty2.EditValue = (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) - (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
            }
        }

        protected void lookUpModelVehicleCode_LostFocus(object sender, EventArgs e)
        {
            MessageBox.Show("Bạn phải chọn chi nhánh hay công ty. (1)-chi nhánh, (0)-Công ty", "Thông báo", MessageBoxButtons.OK);
            //chkZeroOrNone.Focus();
            rdt1.Focus();
        }

        protected void txtVehicleNumber_LostFocus(object sender, EventArgs e)
        {
            if (remind)
            {
                MessageBox.Show("Bạn phải chọn chi nhánh hay công ty. (0)-chi nhánh, (1)-Công ty", "Thông báo", MessageBoxButtons.OK);
                remind = false;
            }//chkZeroOrNone.Focus();
            rdt1.Focus();
        }

        protected void txtQty1_TextChanged(object sender, EventArgs e)
        {
            if (this.txtUnit1.Text.Trim() == "TON" || this.txtUnit1.Text.Trim() == "KG")
            {
                if (Convert.ToDecimal(this.txtQty2.EditValue) == 0)
                {
                    this.txtRate.EditValue = 0;
                }
                else
                {
                    this.txtRate.EditValue = Convert.ToDecimal(this.txtQty1.EditValue) / Convert.ToDecimal(this.txtQty2.EditValue);
                }
            }
            else
            {
                if (Convert.ToDecimal(this.txtQty1.EditValue) == 0)
                {
                    this.txtRate.EditValue = 0;
                }
                else
                {
                    this.txtRate.EditValue = Convert.ToDecimal(this.txtQty2.EditValue) / Convert.ToDecimal(this.txtQty1.EditValue);
                }
            }
        }

        protected override void OnActivated(EventArgs e)
        {
            OpenSerialPort();

            base.OnActivated(e);
        }

        protected override void OnDeactivate(EventArgs e)
        {
            FreeEventSerialPort();

            base.OnDeactivate(e);
        }

        #endregion

        #region Events

        protected void dateScale_DateTimeChanged(object sender, EventArgs e)
        {
            // Load tickets
            LoadNotScaleTicket();
        }

        protected void chkZeroOrNone_CheckedChanged(object sender, EventArgs e)
        {

            this.txtTicketID.Text = TicketID;
        }

        protected void chkManualRequire_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chkManualRequire.Checked)
            {
                // Long
                this.txtRequireName.Location = this.lookUpRequireCode.Location;
                this.txtRequireName.Width = 491;
                this.txtRequireName.Properties.ReadOnly = false;
                this.txtRequireName.Text = String.Empty;
                this.lookUpRequireCode.Visible = false;
                this.txtLimitNumber.Visible = false;
                this.txtRemainNumber.Visible = false;
                this.txtStillNumber.Visible = false;

                // Clear value
                this.lookUpRequireCode.EditValue = null;
                this.lookUpRequireCode.Text = String.Empty;
                this.txtLimitNumber.Text = String.Empty;
                this.txtRemainNumber.Text = String.Empty;
                this.txtStillNumber.Text = String.Empty;
            }
            else
            {
                // Short
                this.txtRequireName.Location = new Point(322, 286);
                this.txtRequireName.Width = 267;
                this.txtRequireName.Properties.ReadOnly = true;
                this.lookUpRequireCode.Visible = true;
                this.txtLimitNumber.Visible = true;
                this.txtRemainNumber.Visible = true;
                this.txtStillNumber.Visible = true;
            }
        }

        protected void chkManualVehicle_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chkManualVehicle.Checked)
            {
                // Long
                this.txtVehicleNumber.Properties.ReadOnly = false;
                this.txtVehicleNumber.Text = String.Empty;
                this.lookUpModelVehicleCode.Visible = false;
            }
            else
            {
                // Short
                this.txtVehicleNumber.Properties.ReadOnly = true;
                this.lookUpModelVehicleCode.Visible = true;
            }
        }

        protected void chkAutomatic_CheckedChanged(object sender, EventArgs e)
        {
            CheckEdit checkBox = sender as CheckEdit;

            // Begin to receive scale automatically if checked.
            //this.cboTicketType.Enabled = !checkBox.Checked;

            if (checkBox.Checked)
            {
                if (chkManual.Checked)
                {
                    this.chkManual.Checked = false;
                }

                if (Convert.ToDecimal(this.numFirstWeight.Value) > 0)
                {
                    // If first scale is available. First is scaled.
                    // Lock first scale box.
                    this.numFirstWeight.Enabled = false;

                    if (Convert.ToDecimal(this.numSecondWeight.Value) > 0)
                    {
                        // Continue 
                        // If the second scale is available. The second is scaled.
                        // Lock second scale box.
                        this.numSecondWeight.Enabled = false;

                    }
                    else
                    {
                        // Else enable the second scale box and focus it.
                        this.numSecondWeight.Enabled = true;
                        this.numSecondWeight.Focus();
                        //  WriteLog("Recevie Second scale");
                    }
                }
                else
                {
                    // Else enable the first scale box and focus it.
                    this.numFirstWeight.Enabled = true;
                    this.numFirstWeight.Focus();
                    // WriteLog("Recevie First scale");
                }
                // OpenSerialPort();
            }
        }

        protected void chkFilterScaleDate_CheckedChanged(object sender, EventArgs e)
        {
            LoadNotScaleTicket();
        }

        /// <summary>
        /// Manual checked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void chkManual_CheckedChanged(object sender, EventArgs e)
        {
            string pass = String.Empty;

            if (this.chkManual.Checked)
            {
                if (ClassInput.InputBox("Chú ý", "Nhập password để 'Nhập tay' số cân", ref pass) == DialogResult.OK)
                {
                    if (pass.ToUpper() == Common.passManualInput)
                    {
                        if (this.chkAutomatic.Checked)
                            this.chkAutomatic.Checked = false;
                        this.numFirstWeight.Enabled = true;
                        this.numSecondWeight.Enabled = true;

                        this.numFirstWeight.Focus();

                        // Set permission
                        this.numFirstWeight.ReadOnly = !Common.UserLogin.Role.Permitted.ManualScale;
                        this.numSecondWeight.ReadOnly = !Common.UserLogin.Role.Permitted.ManualScale;
                    }
                }
            }
            else
            {
                this.numFirstWeight.Enabled = false;
                this.numSecondWeight.Enabled = false;
            }


        }

        protected void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            this.SetValues();
        }

        protected void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            this.SetValues();
        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {
            ScaleTicketDTO ticket = this.gridView1.GetFocusedRow() as ScaleTicketDTO;
            this.PrintMethod(ticket);
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            this.isSelectGrid = false;
            this.AddNew();
        }

        protected void btnSaveAndPrint_Click(object sender, EventArgs e)
        {
            this.SaveMethod();
            //this.txtVehicleNumber.Focus();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            this.SaveMethod();
        }

        protected void btnReset1_Click(object sender, EventArgs e)
        {
            this.numFirstWeight.Value = 0;
            if (!this.numFirstWeight.Enabled)
                this.numFirstWeight.Enabled = true;
            this.numFirstWeight.Focus();
        }

        protected void btnReset2_Click(object sender, EventArgs e)
        {
            this.numSecondWeight.Value = 0;
            if (!this.numSecondWeight.Enabled)
                this.numSecondWeight.Enabled = true;
            this.numSecondWeight.Focus();
        }

        /// <summary>
        /// Look up model vehicle code
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lookUpModelVehicleCode_EditValueChanged(object sender, EventArgs e)
        {
            if (this.lookUpModelVehicleCode.EditValue != null)
            {
                this.txtVehicleNumber.Text = this.lookUpModelVehicleCode.EditValue.ToString();
                this.txtVehicleNumber.Enabled = false;
                var list = (this.lookUpModelVehicleCode.Properties.DataSource as IList<ModelVehicleDTO>);
                if (list != null && list[this.lookUpModelVehicleCode.ItemIndex] != null)
                    this.numFirstWeight.Value = list[this.lookUpModelVehicleCode.ItemIndex].ModelVehicleWeight;

                this.txtScaleTime1.Text = String.Format("{0:d} {0:HH:mm:ss}", DateTime.Now);
                this.numFirstWeight.Enabled = false;
            }
            else
            {
                this.txtVehicleNumber.Text = String.Empty;
                this.txtVehicleNumber.Enabled = true;
            }
        }

        /// <summary>
        /// Look up location code
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lookUpLocationCode_EditValueChanged(object sender, EventArgs e)
        {
            if (this.lookUpLocationCode.EditValue != null)
            {
                this.txtLocationName.Text = this.lookUpLocationCode.EditValue.ToString();
            }
            else
            {
                this.txtLocationName.Text = String.Empty;
            }
        }

        /// <summary>
        /// Look up require code
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lookUpRequireCode_EditValueChanged(object sender, EventArgs e)
        {
            if (this.lookUpRequireCode.EditValue != null)
            {
                string requireCode = this.lookUpRequireCode.Text;
                this.txtRequireName.Text = this.lookUpRequireCode.EditValue.ToString();
                var listRequire = (this.lookUpRequireCode.Properties.DataSource as IList<RequireNumberDTO>);
                if (listRequire != null && listRequire[this.lookUpRequireCode.ItemIndex] != null)
                {
                   // this.txtLimitNumber.EditValue = listRequire[this.lookUpRequireCode.ItemIndex].LimitNumber - _listTemp.Where(x => x.RequireCode == requireCode).Sum(x => x.ActualWeight);
                    this.txtLimitNumber.EditValue = listRequire[this.lookUpRequireCode.ItemIndex].LimitNumber;
                    this.txtRemainNumber.EditValue =listRequire[this.lookUpRequireCode.ItemIndex].RemainNumber;
                    this.txtStillNumber.EditValue = Convert.ToDecimal(this.txtLimitNumber.EditValue) - Convert.ToDecimal(this.txtRemainNumber.EditValue);
                }
            }
            else
            {
                this.txtRequireName.Text = String.Empty;
            }
        }

        /// <summary>
        /// Look up vendor number
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lookUpVendorNumber_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!String.IsNullOrEmpty(this.lookUpVendorNumber.Text))
                {
                    IList<CustomerDTO> vendors = (IList<CustomerDTO>)this.lookUpVendorNumber.Tag;
                    if (vendors != null)
                    {
                        var vendor = vendors.SingleOrDefault(x => x.CustomerName == this.lookUpVendorNumber.Text);
                        if (vendor != null)
                            this.txtVendorName.Text = vendor.CustomerCode;
                        else
                            this.txtVendorName.Text = String.Empty;
                    }
                }
                else
                {
                    this.txtVendorName.Text = String.Empty;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Look up item number
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lookUpItemNumber_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.lookUpItemNumber.Text))
            {
                this.txtQty1.EditValue = 0;
                this.txtQty2.EditValue = 0;
                IList<ItemDTO> items = this.lookUpItemNumber.Tag as IList<ItemDTO>;
                if (items != null)
                {
                    var item = items.SingleOrDefault(x => x.ItemName == this.lookUpItemNumber.Text);
                    if (item != null)
                    {
                        this.txtItemName.Text = item.ItemNumber;
                        this.txtUnit1.Text = item.ItemUnit;
                        this.txtUnit2.Text = item.ItemUnit2;
                    }
                    else
                    {
                        this.txtItemName.Text = string.Empty;
                    }
                }

                if (this.txtUnit1.Text.Trim().StartsWith("TON"))
                {
                    txtQty1.EditValue = ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) - ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit2.Text.Trim().StartsWith("TON"))
                {
                    txtQty2.EditValue = ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) - ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit1.Text.Trim() == "KG")
                {
                    txtQty1.EditValue = (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) - (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit2.Text.Trim() == "KG")
                {
                    txtQty2.EditValue = (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) - (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
            }
            else
            {
                this.txtItemName.Text = String.Empty;
            }
        }

        protected void cboTicketType_SelectedIndexChanged(object sender, EventArgs e)
        {

            this.txtTicketID.Text = TicketID;

        }

        /// <summary>
        /// Unit 1 changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Unit1_TextChanged(object sender, EventArgs e)
        {
            UnitProcessing(1);
        }

        protected void ReduceKg_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.txtUnit1.Text.Trim() == "TON")
                {
                    txtQty1.EditValue = ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) - ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit2.Text.Trim() == "TON")
                {
                    txtQty2.EditValue = ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) - ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit1.Text.Trim() == "KG")
                {
                    txtQty1.EditValue = (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) - (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit2.Text.Trim() == "KG")
                {
                    txtQty2.EditValue = (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) - (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
            }
            catch
            {

            }
        }

        protected void txtKg_LostFocus(object sender, EventArgs e)
        {
            if (txtKg.Text.Length == 0)
            {
                txtKg.EditValue = 0;
            }
        }
        protected void txtPercent_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.txtUnit1.Text.Trim() == "TON")
                {
                    txtQty1.EditValue = ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) - ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit2.Text.Trim() == "TON")
                {
                    txtQty2.EditValue = ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) - ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit1.Text.Trim() == "KG")
                {
                    txtQty1.EditValue = (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) - (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit2.Text.Trim() == "KG")
                {
                    txtQty2.EditValue = (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) - (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
            }
            catch
            {

            }
        }
        protected void txtPercent_LostFocus(object sender, EventArgs e)
        {
            if (txtPercent.Text.Length == 0)
            {
                txtPercent.EditValue = 0;
            }
        }

        protected void txtQty2_TextChanged(object sender, EventArgs e)
        {
            if (this.txtUnit1.Text.Trim() == "TON" || this.txtUnit1.Text.Trim() == "KG")
            {
                if (Convert.ToDecimal(this.txtQty2.EditValue) == 0)
                {
                    this.txtRate.EditValue = 0;
                }
                else
                {
                    this.txtRate.EditValue = Convert.ToDecimal(this.txtQty1.EditValue) / Convert.ToDecimal(this.txtQty2.EditValue);
                }
            }
            else
            {
                if (Convert.ToDecimal(this.txtQty1.EditValue) == 0)
                {
                    this.txtRate.EditValue = 0;
                }
                else
                {
                    this.txtRate.EditValue = Convert.ToDecimal(this.txtQty2.EditValue) / Convert.ToDecimal(this.txtQty1.EditValue);
                }
            }
        }
        /// <summary>
        /// Unit 1 changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Unit2_TextChanged(object sender, EventArgs e)
        {
            UnitProcessing(2);
        }

        /// <summary>
        /// Scale first weight or second weight
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void EditWeightChanged(object sender, EventArgs e)
        {
            // Cast value to decimal
            decimal firstWeight = Convert.ToDecimal(this.numFirstWeight.Value);
            decimal secondWeight = Convert.ToDecimal(this.numSecondWeight.Value);

            if (firstWeight > 0 && secondWeight > 0)
            {
                decimal balance = firstWeight - secondWeight;
                // Debug.WriteLine(balance);
                // Complete 2 scale times.
                this.numBalanceWeight.EditValue = Math.Abs(balance);

                Debug.WriteLine(Math.Abs(balance));

                UnitProcessing(3);

            }
            else
            {
                // Not complete 2 scale times yet.
                this.numBalanceWeight.EditValue = 0;
            }
        }

        protected void numFirstWeight_LostFocus(object sender, EventArgs e)
        {
            if (Convert.ToDecimal(numFirstWeight.Value) > 0)
            {
                // The first is scaled.
                if (this.txtScaleTime1.Text.Length > 0)
                {
                }
                else
                {
                    this.txtScaleTime1.Text = String.Format("{0:d} {0:HH:mm:ss}", DateTime.Now);
                    this.numFirstWeight.Enabled = false;
                }
            }
        }

        protected void numSecondWeight_LostFocus(object sender, EventArgs e)
        {
            if (Convert.ToDecimal(numSecondWeight.Value) > 0)
            {
                // The second is scaled.
                this.txtScaleTime2.Text = String.Format("{0:d} {0:HH:mm:ss}", DateTime.Now);
                this.numSecondWeight.Enabled = false;
                if (this.txtUnit1.Text.Trim() == "TON")
                {
                    txtQty1.EditValue = ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) - ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit2.Text.Trim() == "TON")
                {
                    txtQty2.EditValue = ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) - ((Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) / 1000M) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit1.Text.Trim() == "KG")
                {
                    txtQty1.EditValue = (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) - (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
                if (this.txtUnit2.Text.Trim() == "KG")
                {
                    txtQty2.EditValue = (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) - (Convert.ToDecimal(this.numBalanceWeight.EditValue) - Convert.ToDecimal(this.txtKg.EditValue)) * (Convert.ToDecimal(txtPercent.EditValue) / 100);
                }
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Get status the scale to the library.
        /// </summary>
        /// <returns></returns>
        protected bool GetStatus()
        {
            return this.chkAutomatic.Checked;
        }

        /// <summary>
        /// Parse Data
        /// </summary>
        /// <param name="weight"></param>
        //protected void ParseData(string weight)
        //{
        //    _scaleProcessing.WriteLog("Result: " + weight);

        //    _scaleProcessing.WriteLog(String.Format("First focused: {0}", this.ActiveControl.Equals(this.numFirstWeight)));
        //    _scaleProcessing.WriteLog(String.Format("Second focused: {0}", this.ActiveControl.Equals(this.numSecondWeight)));

        //    //ScaleTicketDTO ticket = this.gridView1.GetFocusedRow() as ScaleTicketDTO;
        //    bool b = (this.txtTicketID.Tag == null);
        //    if (b)
        //    {
        //        // Only scale when add new scale ticket.

        //        // if (!CurrentPO.HasFirstWeight)
        //        if (this.numFirstWeight.Focused)
        //        {
        //            // WriteLog("First weight: " + weight);
        //            this.numFirstWeight.Invoke(new EventHandler(delegate
        //            {
        //                this.numFirstWeight.Value = Int32.Parse(weight);
        //            }));
        //        }
        //        // else if (!CurrentPO.HasSecondWeight)
        //        else if (this.numSecondWeight.Focused)
        //        {
        //            // WriteLog("Second weight: " + weight);
        //            this.numSecondWeight.Invoke(new EventHandler(delegate
        //            {
        //                this.numSecondWeight.Value = Int32.Parse(weight);
        //            }));
        //        }
        //    }
        //}

        private void ClearValues()
        {
            this.txtTicketID.Text = String.Empty;
            this.txtSequence.Text = String.Empty;
            this.txtDescription.Text = String.Empty;
            this.lookUpModelVehicleCode.Text = String.Empty;
            this.lookUpModelVehicleCode.EditValue = null;
            this.txtVehicleNumber.Text = String.Empty;
            this.lookUpItemNumber.Text = String.Empty;
            this.txtItemName.Text = String.Empty;
            this.lookUpVendorNumber.Text = String.Empty;
            this.txtVendorName.Text = String.Empty;
            this.lookUpLocationCode.EditValue = null;
            this.txtQty1.EditValue = 0;
            this.txtQty2.EditValue = 0;
            this.txtUnit1.Text = String.Empty;
            this.txtUnit2.Text = String.Empty;
            // this.cboUnit2.Text = String.Empty;
            this.lookUpRequireCode.Text = String.Empty;
            this.lookUpRequireCode.EditValue = null;
            this.numFirstWeight.Value = 0;
            this.numSecondWeight.Value = 0;
            this.numBalanceWeight.EditValue = 0;
            this.txtKg.EditValue = 0;
            this.txtPercent.EditValue = 0;
            this.txtRequireName.Text = String.Empty;
            this.txtScaleTime1.Text = String.Empty;
            this.txtScaleTime2.Text = String.Empty;

            this.cboTicketType.SelectedIndex = -1;

            this.chkAutomatic.Checked = false;
            this.chkManual.Checked = false;

        }

        private void SetValues()
        {
            if (remindLoad)
            {
                remindLoad = false;
            }
            else
            {
                if (this.gridView1.GetFocusedRow() != null)
                {
                    isSelectGrid = true;
                    ScaleTicketDTO ticket = this.gridView1.GetFocusedRow() as ScaleTicketDTO;
                    if (ticket != null && ticket.ScaleTicketID.CompareTo(this.txtTicketID.Tag) != 0)
                    {
                        //•	Ticket ID
                        //•	Sequence
                        //•	Vehicle number
                        //•	Product ID
                        //•	Product Name
                        //•	Vendor ID
                        //•	Vendor Name
                        //•	Location
                        //•	Qty 1
                        //•	Qty 2
                        //•	Unit 1
                        //•	Unit 2
                        //•	Requirement
                        //•	First Weight 
                        //•	Second Weight
                        //•	Actual Weight 
                        //•	Time 1
                        //•	Time 2
                        //•	Ticket Type

                        this.txtTicketID.Text = ticket.ScaleTicketCode;
                        this.txtTicketID.Tag = ticket.ScaleTicketID;
                        this.txtDescription.Text = ticket.Description;

                        string[] part = this.txtTicketID.Text.Split('-');

                        this.txtSequence.Text = part[4];
                        textSequeneRow = part[4];
                        this.chkManualVehicle.Checked = true;
                        if (ticket.ScaleTicketCode.Substring(6, 1) == "0")
                        {
                            this.rdt0.Checked = true;
                        }
                        else
                        {
                            this.rdt1.Checked = true;
                        }
                        this.txtVehicleNumber.Text = ticket.VehicleID;
                        this.lookUpItemNumber.Text = ticket.ItemName;
                        this.txtItemName.Text = ticket.ItemNumber;
                        this.lookUpVendorNumber.Text = ticket.CustomerName;
                        this.txtVendorName.Text = ticket.CustomerCode;
                        this.lookUpLocationCode.Text = ticket.LocationCode;
                        this.txtQty1.EditValue = ticket.Quantity1;
                        this.txtQty2.EditValue = ticket.Quantity2;
                        this.txtUnit1.Text = ticket.ItemUnit;
                        this.txtUnit2.Text = ticket.ItemUnit2;
                        this.txtKg.EditValue = ticket.KgReduce;
                        this.txtPercent.EditValue = ticket.PercentReduce;
                        // this.cboUnit2.Text = ticket.ItemUnit2;

                        this.chkManualRequire.Checked = String.IsNullOrEmpty(ticket.RequireCode);

                        this.lookUpRequireCode.Text = ticket.RequireCode;
                        this.txtRequireName.Text = ticket.RequireName;
                        this.txtLimitNumber.EditValue = ticket.RequireLimit;
                        this.numFirstWeight.Value = ticket.FirstWeight;
                        this.numSecondWeight.Value = ticket.SecondWeight;
                        this.numBalanceWeight.EditValue = ticket.ActualWeight;

                        this.txtScaleTime1.Text = String.Format("{0:d} {0:HH:mm:ss}", ticket.InHour);
                        if (ticket.OutHour != null)
                            this.txtScaleTime2.Text = String.Format("{0:d} {0:HH:mm:ss}", ticket.OutHour);
                        else
                            this.txtScaleTime2.Text = String.Empty;

                        string ticketType = ticket.ScaleTicketCode.Substring(0, 2);
                        switch (ticketType)
                        {
                            case "PR":
                                this.cboTicketType.SelectedIndex = 0;
                                break;
                            case "CI":
                                this.cboTicketType.SelectedIndex = 1;
                                break;
                            case "SI":
                                this.cboTicketType.SelectedIndex = 2;
                                break;
                            case "TR":
                                this.cboTicketType.SelectedIndex = 3;
                                break;
                            case "TI":
                                this.cboTicketType.SelectedIndex = 4;
                                break;
                        }


                        if (chkAutomatic.Checked) chkAutomatic.Checked = false;
                        if (chkManual.Checked) chkManual.Checked = false;

                        this.ControlButton(true);
                        this.btnSaveAndPrint.Enabled = true;
                        this.lookUpRequireCode.Enabled = true;
                        this.txtRequireName.Enabled = true;
                        if (this.numSecondWeight.Text == "0")
                        {
                            this.btnSaveAndPrint.Enabled = true;
                            this.btnSave.Enabled = true;
                            this.txtQty1.Enabled = true;
                            this.txtQty2.Enabled = true;
                            this.cboUnit2.Enabled = true;
                            this.lookUpItemNumber.Enabled = true;
                            this.lookUpLocationCode.Enabled = true;
                            this.lookUpVendorNumber.Enabled = true;
                            this.chkManualRequire.Enabled = true;
                            this.lookUpRequireCode.Enabled = true;
                            this.txtRequireName.Enabled = true;
                        }
                        // Status
                        this.labelStatus.Text = "Đang chọn phiếu cân.";
                    }
                }
            }
        }

        private ScaleTicketDTO SetData()
        {
            ScaleTicketDTO ticket;
            decimal firstWeight = Convert.ToDecimal(this.numFirstWeight.Value);
            decimal secondWeight = Convert.ToDecimal(this.numSecondWeight.Value);
            string ticketType = "XX";
            if (this.txtTicketID.Tag == null)
            {
                // New Item
                ticket = new ScaleTicketDTO() { ScaleTicketCode = TicketID, IsNew = true };
                
                ticket.ScaleTicketCode = this.txtTicketID.Text;
            }
            else
            {
                ticket = this.gridView1.GetFocusedRow() as ScaleTicketDTO; // get TicketDTO from Grid selected

                // if there is change selected scale type 
                if (this.cboTicketType.SelectedIndex > -1)
                {
                    switch (this.cboTicketType.SelectedIndex)
                    {
                        case 0:
                            ticketType = "PR-";
                            break;
                        case 1:
                            ticketType = "CI-";
                            break;
                        case 2:
                            ticketType = "SI-";
                            break;
                        case 3:
                           // if (firstWeight > secondWeight)
                            //{
                                // Receive
                                ticketType = "TR-";
                           // }
                            //else
                            //{
                                // Invoice
                                break;
                        case 4:
                                ticketType = "TI-";
                           // }
                            break;
                    }
                }
                ticket.ScaleTicketCode = ticketType + this.txtTicketID.Text.Substring(3);
            }

            //•	Ticket ID
            //•	Sequence
            //•	Vehicle number
            //•	Product ID
            //•	Product Name
            //•	Vendor ID
            //•	Vendor Name
            //•	Location
            //•	Qty 1
            //•	Qty 2
            //•	Unit 1
            //•	Unit 2
            //•	Requirement
            //•	First Weight 
            //•	Second Weight
            //•	Actual Weight 
            //•	Time 1
            //•	Time 2
            //•	Ticket Type

            // ticket.Sequence = this.txtSequence.Text = "xxx";
            if (isSelectGrid == false)
            {
                ticket.ScaleTicketID = Guid.NewGuid();
            }

           
            ticket.VehicleID = this.txtVehicleNumber.Text;
            ticket.ItemNumber = this.txtItemName.Text;
            ticket.ItemName = this.lookUpItemNumber.Text;
            ticket.CustomerCode = this.txtVendorName.Text;
            ticket.CustomerName = this.lookUpVendorNumber.Text;

            ticket.LocationCode = this.lookUpLocationCode.Text;
            ticket.LocationName = this.txtLocationName.Text;
            ticket.Quantity1 = Convert.ToDecimal(this.txtQty1.EditValue);
            ticket.Quantity2 = Convert.ToDecimal(this.txtQty2.EditValue);
            ticket.ItemUnit = this.txtUnit1.Text;
            ticket.ItemUnit2 = this.txtUnit2.Text;
            // ticket.ItemUnit2 = this.cboUnit2.Text;
            ticket.RequireCode = this.lookUpRequireCode.Text;
            ticket.RequireName = this.txtRequireName.Text;
            ticket.KgReduce = Convert.ToDecimal(this.txtKg.EditValue);
            ticket.PercentReduce = Convert.ToDecimal(this.txtPercent.EditValue);
            ticket.Description = this.txtDescription.Text;
            ticket.KgReduce = Convert.ToDecimal(this.txtKg.EditValue);
            ticket.PercentReduce = Convert.ToDecimal(this.txtPercent.EditValue);
            ticket.ModifiedDate = DateTime.Now;
            decimal limitNumber;
            if (Decimal.TryParse(this.txtLimitNumber.Text, out limitNumber))
                ticket.RequireLimit = limitNumber;

            ticket.FirstWeight = firstWeight;
            ticket.SecondWeight = secondWeight;
            ticket.ActualWeight = Convert.ToDecimal(this.numBalanceWeight.EditValue);

            ticket.InHour = DateTime.Parse(this.txtScaleTime1.Text);
            DateTime dateOut;
            if (DateTime.TryParse(this.txtScaleTime2.Text, out dateOut))
            {
                ticket.OutHour = dateOut;
            }
            else
            {
                ticket.OutHour = ticket.InHour;
            }

            ticket.ModifiedBy = Common.UserLogin.Username;

            return ticket;
        }

        /// <summary>
        /// Unit processing
        /// </summary>
        private void UnitProcessing(short i)
        {
            // Process Unit 1
            if ((i & 1) == 1)
            {
                if (this.txtUnit1.Text.Trim() == "KG")
                {
                    this.txtQty1.EditValue = Convert.ToDecimal(this.numBalanceWeight.EditValue);
                    this.txtQty1.Enabled = false;
                }
                else if (this.txtUnit1.Text.Trim() == "TẤN")
                {
                    this.txtQty1.EditValue = Convert.ToDecimal(this.numBalanceWeight.EditValue) / 1000M;
                    this.txtQty1.Enabled = false;
                }
                else
                    this.txtQty1.Enabled = true;
            }

            // Process Unit 2
            if ((i & 2) == 2)
            {
                if (this.txtUnit2.Text.Trim() == "KG")
                {
                    this.txtQty2.EditValue = Convert.ToDecimal(this.numBalanceWeight.EditValue);
                    this.txtQty2.Enabled = false;
                }
                else if (this.txtUnit2.Text.Trim() == "TẤN")
                {
                    this.txtQty2.EditValue = Convert.ToDecimal(this.numBalanceWeight.EditValue) / 1000M;
                    this.txtQty2.Enabled = false;
                }
                else
                    this.txtQty2.Enabled = true;
            }
        }

        private void ControlButton(bool b)
        {
            // Enable / Disable button
            //  this.btnNew.Enabled = b;
            this.btnSaveAndPrint.Enabled = b;
            this.btnSave.Enabled = b;
            this.btnPrint.Enabled = !b;

            this.chkManualVehicle.Enabled = b;
            this.txtVehicleNumber.Enabled = b;
            this.lookUpItemNumber.Enabled = b;
            this.lookUpVendorNumber.Enabled = b;
            this.lookUpLocationCode.Enabled = b;
            this.cboTicketType.Enabled = b;
            this.txtQty1.Enabled = b;
            this.txtQty2.Enabled = b;
            this.txtUnit1.Enabled = b;
            this.txtUnit2.Enabled = b;
            //this.cboUnit2.Enabled = b;
            this.lookUpRequireCode.Enabled = b;
            this.txtRequireName.Enabled = b;
            this.cboTicketType.Enabled = b;
            this.btnPrint.Enabled = false;

            this.chkManualRequire.Enabled = b;
        }

        private void ExportTicket(ScaleTicketDTO ticket)
        {
            string filename = ticket.ScaleTicketCode;
            //string typeScale = ticket.ScaleTicketCode.Substring(ticket.ScaleTicketCode.Length - 2, 2) + "-";
            //string name = ticket.ScaleTicketCode.Substring(0,ticket.ScaleTicketCode.Length -3);
            //ticket.ScaleTicketCode = typeScale + name;
            // Export Excel file
            table.Rows.Clear();
            table.Rows.Add(new object[] {
                        ticket.ScaleTicketCode,
                        FontConversion.ConvertUnicode2VNI(ticket.RequireName),
                        ticket.ItemNumber,
                        FontConversion.ConvertUnicode2VNI(ticket.ItemName),
                        ticket.CustomerCode,
                        FontConversion.ConvertUnicode2VNI(ticket.CustomerName),
                        ticket.InHour,
                        ticket.OutHour,
                        ticket.FirstWeight,
                        ticket.SecondWeight,
                        ticket.ActualWeight,
                        ticket.VehicleID,
                        ticket.LocationCode,
                        ticket.Quantity1,
                        FontConversion.ConvertUnicode2VNI(ticket.ItemUnit),
                        ticket.Quantity2,
                        FontConversion.ConvertUnicode2VNI(ticket.ItemUnit2),
                        Math.Round((decimal)(ticket.Quantity2 > 0 ? ticket.Quantity1 / ticket.Quantity2 : ticket.Quantity1), 2)
                    });
            this.ExportToExcel(filename, Convert.ToInt32(ticket.ScaleTicketCode.Substring(6, 1)));
        }

        private void ExportTicket(IEnumerable<ScaleTicketDTO> list, int zero)
        {
            string filename = string.Empty;

            // Export Excel file
            table.Rows.Clear();
            list = list.Where(x => x.ScaleTicketCode.Substring(3, 1) == zero.ToString());


            if (list.Count() > 0)
            {
                foreach (var ticket in list)
                {
                    if (filename == string.Empty)
                        filename = ticket.RequireCode + String.Format("{0:yyyyMMdd}", DateTime.Now);

                    table.Rows.Add(new object[] {
                        ticket.ScaleTicketCode,
                        FontConversion.ConvertUnicode2VNI(ticket.RequireName),
                        ticket.ItemNumber,
                        FontConversion.ConvertUnicode2VNI(ticket.ItemName),
                        ticket.CustomerCode,
                        FontConversion.ConvertUnicode2VNI(ticket.CustomerName),
                        ticket.InHour,
                        ticket.OutHour,
                        ticket.FirstWeight,
                        ticket.SecondWeight,
                        ticket.ActualWeight,
                        ticket.VehicleID,
                        ticket.LocationCode,
                        ticket.Quantity1,
                        FontConversion.ConvertUnicode2VNI(ticket.ItemUnit),
                        ticket.Quantity2,
                        FontConversion.ConvertUnicode2VNI(ticket.ItemUnit2),
                        Math.Round((decimal)(ticket.Quantity2 > 0 ? ticket.Quantity1 / ticket.Quantity2 : ticket.Quantity1), 2)
                    });
                }

                this.ExportToExcel(filename, zero);
            }
        }

        private void ExportToExcel(string filename, int zero)
        {
            try
            {
              
                //begin save Excel to storage Path
                string filelocation = String.Format("{0}/{1}/{2}.xls", Common.storagePath, zero, filename);

                if (File.Exists(filelocation))
                {
                    DialogResult result = MessageBox.Show("File này đã xuất Excel, bạn có muốn xóa đi và xuất lại không?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.No)
                        return;

                    File.Delete(filelocation);
                }

                //string[] headers = new string[] {
                //            "[Mã số phiếu cân] Text(100)",
                //            "[Số yêu cầu] Text(200)",
                //            "[Mã hàng hóa] Text(30)",
                //            "[Tên hàng hóa] Text(200)",
                //            "[Mã vendor] Text(30)",
                //            "[Tên vendor] Text(200)",
                //            "[Giờ xe vào] Date",
                //            "[Giờ xe ra] Date",
                //            "[Vào] Number",
                //            "[Ra] Number",
                //            "[Trọng lượng (kg)] Number",
                //            "[Số xe] Text(10)",
                //            "[Kho] Text(100)",
                //            "[Số lượng 1] Number",
                //            "[ĐVT 1] Text(30)",
                //            "[Số lượng 2] Number",
                //            "[ĐVT 2] Text(30)",
                //            "[Đơn trọng] Number"
                //        };

                //string[] headers = new string[] {
                //            "F1 Text(100)",
                //            "F2 Text(200)",
                //            "F3 Text(30)",
                //            "F4 Text(200)",
                //            "F5 Text(30)",
                //            "F6 Text(200)",
                //            "F7 Date",
                //            "F8 Date",
                //            "F9 Number",
                //            "F10 Number",
                //            "F11 Number",
                //            "F12 Text(10)",
                //            "F13 Text(100)",
                //            "F14 Number",
                //            "F15 Text(30)",
                //            "F16 Number",
                //            "F17 Text(30)",
                //            "F18 Number"
                //        };

                // ImportData.CreateExcelTable(filelocation, "Sheet1", headers);
                // ImportData.TableToExcel(filelocation, "Sheet1", table);

                //Create the data set and table
                DataSet ds = new DataSet("Sheet1");

                //Set the locale for each
                ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
                table.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
                table.TableName = "Sheet1";

                //Add the table to the data set
                ds.Tables.Add(table);

                ExcelLibrary.DataSetHelper.HDR = false;
                ExcelLibrary.DataSetHelper.CreateWorkbook(filelocation, ds);

                ds.Tables.Clear();
                ds.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void AddNew()
        {
            this.ClearValues();

            this.txtTicketID.Text = TicketID;

            if (this.txtTicketID.Tag != null)
                this.txtTicketID.Tag = null;

            this.chkManualRequire.Visible = true;
            this.chkManualRequire.Checked = true;

            this.ControlButton(true);

            // Set Status
            this.labelStatus.Text = "  Tạo phiếu cân mới.";
        }

        private void PrintMethod(ScaleTicketDTO ticket)
        {
            decimal rate;
            string scaleType = String.Empty;
            string scaleType2 = String.Empty;
            string unit = String.Empty;

            // Print ticket type
            if (this.cboTicketType.EditValue != null)
            {
                switch (this.cboTicketType.SelectedIndex)
                {
                    case 0:
                        scaleType = "NHẬP (PR)";
                        scaleType2 = "PR-";
                        break;
                    case 1:
                        scaleType = "XUẤT SỬ DỤNG (CI)";
                        scaleType2 = "CI-";
                        break;
                    case 2:
                        scaleType = "XUẤT BÁN (SI)";
                        scaleType2 = "SI-";
                        break;
                    case 3:
                        // Receive
                        scaleType = "CHUYỂN (NHẬP: TR)";
                        scaleType2 = "TR-";
                        break;
                    case 4:
                        scaleType = "CHUYỂN (XUẤT: TI)";
                        scaleType2 = "TI-";
                        break;
                }
            }
            else
            {
                scaleType = "Không xác định";
            }

            if (this.txtTicketID.Text.Substring(6, 1) == "0")
            {
                unit = "0";
            }
            else
            {
                unit = "1";
            }

            try
            {
                ReportDocument report = new ReportDocument();
                report.Load(Application.StartupPath + @"\Reports\crtScaleTicket.rpt");
                report.SetDataSource(CollectionExtensions<ScaleTicketDTO>.ConvertToDataTable(new List<ScaleTicketDTO>() { ticket }, "ScaleTicket"));
                rate = Convert.ToDecimal(txtRate.EditValue);
                report.SetParameterValue("weightRate", rate);
                report.SetParameterValue("ScaleType", scaleType);
                report.SetParameterValue("Unit", unit);
                report.SetParameterValue("typeScale", scaleType2);
                SettingApp setting = new SettingApp();

                if (Common.CheckPrinter(setting.ReceiptPrintName))
                    report.PrintOptions.PrinterName = setting.ReceiptPrintName;
                report.PrintOptions.ApplyPageMargins(new CrystalDecisions.Shared.PageMargins(setting.MarginLeft, setting.MarginTop, setting.MarginRight, setting.MarginBottom));

                if (setting.IsPreviewReceiptPrint)
                {
                    FormPrintPreview form = new FormPrintPreview(report);
                    form.ShowDialog();
                }
                else
                {
                    report.PrintToPrinter(1, false, 0, 0);
                }
                
            }
            catch (Exception ex)
            {
                Common.ShowAlert(ex.Message);
            }
        }

        private bool ValidationMethod(IList<ScaleTicketDTO> list)
        {

            // Check scale type
            decimal firstWeight = Convert.ToDecimal(this.numFirstWeight.Value);
            decimal secondWeight = Convert.ToDecimal(this.numSecondWeight.Value);
            decimal balanceWeight = Convert.ToDecimal(this.numBalanceWeight.EditValue);
            if (balanceWeight > 0)
            {
                if (firstWeight > secondWeight) // lần 1 > lần 2 -> nhập hàng
                {
                    // Receive
                    if (this.cboTicketType.SelectedIndex > 0 && this.cboTicketType.SelectedIndex < 3 || this.cboTicketType.SelectedIndex == 4)
                    {
                        MessageBox.Show("Bạn đang chọn xuất hàng, cân vào phải nhỏ hơn cân ra!", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
                else //xuất hàng
                {
                    // Invoices
                    if (this.cboTicketType.SelectedIndex == 0 || this.cboTicketType.SelectedIndex == 3)
                    {
                        MessageBox.Show("Bạn đang nhập hàng, cân vào phải lớn hơn cân ra!", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
                if (Convert.ToDecimal(this.txtQty1.EditValue) == 0)
                {
                    bool? result = Common.ShowYesNoQuestion("Bạn chưa nhập số lượng 1. Bạn có muốn nhập không?");
                    if (result.HasValue && result.Value)
                    {
                        return false;
                    }
                }
                if (Convert.ToDecimal(this.txtQty2.EditValue) == 0)
                {
                    bool? result = Common.ShowYesNoQuestion("Bạn chưa nhập số lượng 2. Bạn có muốn nhập không?");
                    if (result.HasValue && result.Value)
                    {
                        return false;
                    }
                }
            }

          

            if (cboTicketType.EditValue == null)
            {
                Common.ShowAlert("Bạn chưa chọn loại phiếu cân.");
                return false;
            }
            // Check null

            if (firstWeight > 0 && secondWeight > 0)
            {

                if (String.IsNullOrEmpty(this.lookUpItemNumber.Text))
                {
                    MessageBox.Show("Bạn chưa chọn hàng hóa cân!", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }

                if (String.IsNullOrEmpty(this.lookUpVendorNumber.Text))
                {
                    MessageBox.Show("Bạn chưa chọn khách hàng!", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }

                if (String.IsNullOrEmpty(this.lookUpLocationCode.Text))
                {
                    MessageBox.Show("Bạn chưa chọn kho!", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }

            return true;
        }

        private void SaveMethod()
        {
            IList<ScaleTicketDTO> list = this.gridControlTickets.DataSource as IList<ScaleTicketDTO>;
            RequireNumberDataAccess _dataAccessRequire = new RequireNumberDataAccess();
            decimal n = Convert.ToDecimal(this.numBalanceWeight.EditValue);
            bool result;
            if (!ValidationMethod(list)) return;

            // Check limit in group
            decimal limitNumber;
            decimal requireNumber;
            decimal requiredScale;
            Decimal.TryParse(this.txtLimitNumber.Text, out requireNumber);
            Decimal.TryParse(this.txtRemainNumber.Text, out requiredScale);
            limitNumber = requireNumber - requiredScale;
            //if (Decimal.TryParse(this.txtLimitNumber.Text, out limitNumber))
            // {
            string requireCode = this.lookUpRequireCode.Text;
            if (!String.IsNullOrEmpty(requireCode))
            {
                decimal actualWeight = Convert.ToDecimal(this.numBalanceWeight.EditValue);
                // decimal weight = _listTemp.Where(x => x.RequireCode == requireCode).Sum(x => x.ActualWeight) + actualWeight;
                if (actualWeight > limitNumber)
                {
                    MessageBox.Show("Bạn đã cân vượt quá mức yêu cầu cho phép!", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   // return false;
                }
            }
           

            //Test file store Path
            if (!Directory.Exists(Common.storagePath + "/0"))
            {
                Common.ShowAlert("Không tìm thấy đường dẫn: " + Common.storagePath + "  , để lưu Excel phiếu cân. Xin cấu hình lại đường dẫn trước khi cân.");
                return;
            }
            else if (!Directory.Exists(Common.storagePath + "/1"))
            {
                Common.ShowAlert("Không tìm thấy đường dẫn: " + Common.storagePath + "  , để lưu Excel phiếu cân. Xin cấu hình lại đường dẫn trước khi cân.");
                return;
            }

            // Save ticket
            try
            {
                if (chkAutomatic.Checked) chkAutomatic.Checked = false;
                ScaleTicketDTO ticket = SetData();
                var listRequire = (this.lookUpRequireCode.Properties.DataSource as IList<RequireNumberDTO>);
                IScaleTicketDataAccess dataAccess = (svc.GetService(typeof(IScaleTicketDataAccess)) as IScaleTicketDataAccess);

                if (ticket.IsNew)
                {
                    // if chkManualRequire, insert to location table.
                    if (dataAccess.Add(ticket))
                    {
                        
                        // Reset values
                        this.chkManual.Checked = false;
                        ticket.IsNew = false;
                        ticket.IsEdited = false;

                        this.PrintMethod(ticket);

                        // Add to grid
                        if (ticket.SecondWeight == 0)
                            list.Add(ticket);
                        else
                            _listTemp.Add(ticket);
                        if (ticket.SecondWeight > 0)
                        {
                            _require = listRequire[this.lookUpRequireCode.ItemIndex];
                            _require.RemainNumber = Convert.ToInt32(this.txtRemainNumber.Text) + Convert.ToInt32(this.numBalanceWeight.EditValue);
                            result = _dataAccessRequire.Edit(_require);
                            if (result)
                            {
                            }
                            else
                            {
                                Common.ShowAlert("Cập nhật số lượng yêu cầu không thành công");
                            }
                        }

                        // Clear and new
                        this.AddNew();
                        // Status
                        this.labelStatus.Text = "  Lưu phiếu cân thành công.";

                    }
                    else
                    {
                        Common.ShowAlert("Lỗi lưu phiếu cân");
                        return;
                    }
                }
                else if (ticket.IsEdited)
                {
                    if (dataAccess.Edit(ticket))
                    {
                        this.chkManual.Checked = false;
                        this.chkManualRequire.Checked = false;

                        this.PrintMethod(ticket);
                       
                        if (ticket.SecondWeight > 0)
                        {
                            list.Remove(ticket);
                            _listTemp.Add(ticket);
                            _require = listRequire[this.lookUpRequireCode.ItemIndex];
                            _require.RemainNumber = Convert.ToInt32(this.txtRemainNumber.Text) + Convert.ToInt32(this.numBalanceWeight.EditValue);                           
                            result = _dataAccessRequire.Edit(_require);
                            if (result)
                            {
                            }
                            else
                            {
                                Common.ShowAlert("Cập nhật số lượng yêu cầu không thành công");
                            }

                        }
                    }
                    else
                    {
                        this.labelStatus.Text = "  Lưu phiếu cân thất bại.";
                        Common.ShowAlert("Lưu phiếu cân thất bại.");
                        return;
                    }
                }


                // Update grid
                this.gridView1.RefreshData();
                this.gridView1.SetFocusedRowModified();
                this.gridView1.SelectRow(list.IndexOf(ticket));
                int getBranch;
                if (this.rdt0.Checked)
                {
                    getBranch = 0;
                }
                else
                {
                    getBranch = 1;
                }
                // Export to Excel if balance > 0 and second weight > 0
                //decimal n = this.numBalanceWeight.EditValue.;
                if (n > 0)
                {
                    if (this._exportViaRequire && !string.IsNullOrEmpty(ticket.RequireCode))
                        this.ExportTicket(_listTemp.Where(x => x.RequireCode == ticket.RequireCode), getBranch);
                    else
                        this.ExportTicket(ticket);

                    // Status
                    this.labelStatus.Text = "  Xuất file Excel thành công.";
                }
                this.ControlButton(false);
                this.btnNew.Enabled = true;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Format: P1-0/1-yyyyMMdd-autoid-PR/CI/SI/TR/TI
        /// </summary>
        private string TicketID
        {
            get
            {
                string ticketType = "XX";
                decimal firstWeight = Convert.ToDecimal(this.numFirstWeight.Value);
                decimal secondWeight = Convert.ToDecimal(this.numSecondWeight.Value);

                //Loi's Code
                if (this.cboTicketType.SelectedIndex > -1)
                {
                    switch (this.cboTicketType.SelectedIndex)
                    {
                        case 0:
                            ticketType = "PR";
                            break;
                        case 1:
                            ticketType = "CI";
                            break;
                        case 2:
                            ticketType = "SI";
                            break;
                        case 3:
                           // if (firstWeight > secondWeight)
                           // {
                                // Receive
                                ticketType = "TR";
                            break;
                           // }
                            //else
                            //{
                                // Invoice
                        case 4:
                                ticketType = "TI";
                           // }
                            break;
                    }
                }

                IScaleTicketDataAccess dataAccess = (svc.GetService(typeof(IScaleTicketDataAccess)) as IScaleTicketDataAccess);
                if (isSelectGrid == false)
                {
                    this.txtSequence.EditValue = dataAccess.GetMaxCode(Common.workstation);
                }
                else
                {
                    this.txtSequence.EditValue = Convert.ToInt32(textSequeneRow);
                }
                int getBranch;
                if (this.rdt0.Checked)
                {
                    getBranch = 0;
                }
                else
                {
                    getBranch = 1;
                }
                string ticketID = String.Format("{0}-{1}-{2}-{3:yyyyMMdd}-{4:000}",
                    ticketType,
                    Common.workstation,
                    getBranch,
                    DateTime.Today,
                    Convert.ToInt32(this.txtSequence.EditValue)
                    );

                return ticketID;
            }
        }

        private void LoadNotScaleTicket()
        {
            object tickets;
            if (this.chkFilterScaleDate.Checked)
            {
                // Load tickets
                tickets = (svc.GetService(typeof(IScaleTicketDataAccess)) as IScaleTicketDataAccess).GetList(Common.workstation, null);
                this.dateScale.Enabled = false;
            }
            else
            {
                this.dateScale.Enabled = true;
                //this.dateScale.DateTime = DateTime.Now;
                tickets = (svc.GetService(typeof(IScaleTicketDataAccess)) as IScaleTicketDataAccess).GetList(Common.workstation, this.dateScale.DateTime);
            }
            this.gridControlTickets.DataSource = tickets;

            _listTemp = new List<ScaleTicketDTO>();
        }
        #endregion

        #region Methods Port
        public void OpenSerialPort()
        {
            try
            {
                if (!Common.Port.IsOpen)
                {
                    Common.Port.Open();
                }
                Common.Port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);
                //  WriteLog("Open port");

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        public void FreeEventSerialPort()
        {
            try
            {
                Common.Port.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);
                // WriteLog("Clost port");
            }
            catch (Exception ex)
            {
                Common.ShowAlert(ex.Message);
            }
        }

        public void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                bool scaleStatus = this.chkAutomatic.Checked;
                // WriteLog("Start receive data 1");
                if (scaleStatus)
                {
                    //  WriteLog("Start receive data");
                    string dataReceived = Common.Port.ReadExisting();

                    _data = String.Concat(_data, dataReceived);

                    // WriteLog("1 : " + _data);

                    // I change for ok all of cases.

                    // Get index of the start byte and the end byte;
                    //byte sByte = 0x47; //G
                    //byte eByte = 0x6B;
                    int startIdx = _data.IndexOf(Convert.ToChar(Common.StartByte));    // index = 0x47;

                    if (startIdx >= 0)
                    {
                        //  WriteLog("2.Start string: " + _data);

                        _data = _data.Substring(startIdx + 1);
                    }

                    int endIdx = _data.IndexOf(Convert.ToChar(Common.EndByte));
                    // Get String with End Index and Print It.
                    if (endIdx >= 0)
                    {
                        // Process the skip byte and end string.
                        _data = _data.Substring(Common.SkipBytes, endIdx);
                        _data = _data.Trim();

                        // WriteLog("3.Complete string: " + _data);

                        // Print it

                        ParseData(_data);

                        _data = String.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Receive data failed. Error details: " + ex.Message);
            }
        }

        private void ParseData(string weight)
        {
            //WriteLog("Result: " + weight);

            //WriteLog(String.Format("First focused: {0}", this.ActiveControl.Equals(this.numFirstWeight)));
            //WriteLog(String.Format("Second focused: {0}", this.ActiveControl.Equals(this.numSecondWeight)));

            //ScaleTicketDTO ticket = this.gridView1.GetFocusedRow() as ScaleTicketDTO;
            // bool b = (this.txtTicketID.Tag == null);
            // if (b)
            //{
            // Only scale when add new scale ticket.

            // if (!CurrentPO.HasFirstWeight)
            if (this.ActiveControl.Equals(this.numFirstWeight))
            {
                // WriteLog("First weight: " + weight);
                this.numFirstWeight.Invoke(new EventHandler(delegate
                {
                    this.numFirstWeight.Text = Int32.Parse(weight).ToString();
                }));
            }
            // else if (!CurrentPO.HasSecondWeight)
            else if (this.ActiveControl.Equals(this.numSecondWeight))
            {
                //WriteLog("Second weight: " + weight);
                this.numSecondWeight.Invoke(new EventHandler(delegate
                {
                    this.numSecondWeight.Text = Int32.Parse(weight).ToString();
                }));
            }
            //}
        }

        public void WriteLog(string message)
        {
            if (!File.Exists(Common.logfile))
                File.Create(Common.logfile);
            using (StreamWriter w = File.AppendText(Common.logfile))
            {
                w.WriteLine(String.Format("{0:d} {0:HH:mm} - {1}", DateTime.Now, message));
                // Close the writer and underlying file.
                w.Flush();
                w.Close();
            }
        }
        #endregion

    }
}